using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Price;
using B.S.NewMedical.Api.Read.DTOS.Price;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Price
{
    /// <summary>
    /// 获取价格条目处理器
    /// </summary>
    public class GetPriceItemsHandler : IRequestHandler<GetPriceItemsCommand, ApiResult<List<PriceItemDto>>>
    {
        private readonly IBaseRepository<PriceItem> _priceItemRepository;
        private readonly IBaseRepository<PriceServiceType> _serviceTypeRepository;
        private readonly ILogger<GetPriceItemsHandler> _logger;
        private readonly IMapper _mapper;

        public GetPriceItemsHandler(
            IBaseRepository<PriceItem> priceItemRepository,
            IBaseRepository<PriceServiceType> serviceTypeRepository,
            ILogger<GetPriceItemsHandler> logger,
            IMapper mapper)
        {
            _priceItemRepository = priceItemRepository;
            _serviceTypeRepository = serviceTypeRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<PriceItemDto>>> Handle(GetPriceItemsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取价格条目列表，服务类型ID：{TypeId}", request.TypeId);

                // 查询条件 - 只查询未删除的记录
                var query = _priceItemRepository.GetAll()
                    .Where(pi => !pi.IsDeleted);

                // 服务类型信息
                PriceServiceType serviceType = null;

                // 如果指定了TypeId，则按服务类型过滤
                if (request.TypeId.HasValue && request.TypeId.Value > 0)
                {
                    int typeId = request.TypeId.Value;
                    serviceType = await _serviceTypeRepository.GetAll()
                        .FirstOrDefaultAsync(st => st.Id == typeId && !st.IsDeleted, cancellationToken);

                    if (serviceType == null)
                    {
                        return new ApiResult<List<PriceItemDto>>
                        {
                            Code = ApiEnum.Error,
                            Msg = "服务类型不存在或已删除"
                        };
                    }

                    // 按TypeId过滤
                    query = query.Where(pi => pi.TypeId == typeId);
                }

                // 获取价格条目列表
                var priceItems = await query
                    .OrderBy(pi => pi.PriceMin) // 按最低价排序
                    .ToListAsync(cancellationToken);

                // 如果没有指定服务类型，需要获取所有相关的服务类型信息
                Dictionary<int, PriceServiceType> serviceTypes = new Dictionary<int, PriceServiceType>();
                
                if (serviceType == null)
                {
                    // 获取所有涉及到的服务类型ID
                    var typeIds = priceItems.Select(p => p.TypeId).Distinct().ToList();
                    
                    // 批量查询所有需要的服务类型
                    var types = await _serviceTypeRepository.GetAll()
                        .Where(st => typeIds.Contains(st.Id) && !st.IsDeleted)
                        .ToListAsync(cancellationToken);
                    
                    // 转为字典便于查询
                    serviceTypes = types.ToDictionary(t => t.Id);
                }

                // 映射到DTO
                var result = priceItems.Select(pi => 
                {
                    // 获取当前项目的服务类型
                    var currentServiceType = serviceType ?? 
                        (serviceTypes.ContainsKey(pi.TypeId) ? serviceTypes[pi.TypeId] : null);
                    
                    string typeName = currentServiceType?.Name ?? "未知服务类型";
                    
                    return new PriceItemDto
                    {
                        Id = pi.Id,
                        TypeId = pi.TypeId,
                        TypeName = typeName,
                        ServiceName = pi.ServiceName,
                        PriceMin = pi.PriceMin,
                        PriceMax = pi.PriceMax,
                        PromoText = pi.PromoText,
                        UpdatedAt = pi.UpdatedAt,
                        CategoryTag = GetCategoryTag(typeName)
                    };
                }).ToList();

                return new ApiResult<List<PriceItemDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取价格条目列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取价格条目列表时发生异常");
                return new ApiResult<List<PriceItemDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取价格条目列表失败：" + ex.Message
                };
            }
        }

        // 根据服务类型名称获取分类标签
        private string GetCategoryTag(string serviceTypeName)
        {
            if (serviceTypeName.Contains("药") || serviceTypeName.Contains("处方"))
                return "药品";
            else if (serviceTypeName.Contains("检查") || serviceTypeName.Contains("超声") || serviceTypeName.Contains("血液"))
                return "检查";
            else
                return "诊疗";
        }
    }
} 